package com.jadcon.bedbreakfast.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.jadcon.bedbreakfast.domain.Customer;
import com.jadcon.bedbreakfast.domain.CustomerService;
import com.jadcon.bedbreakfast.domain.PhoneNumber;
import com.jadcon.bedbreakfast.domain.PhoneType;
import com.jadcon.bedbreakfast.domain.State;

@Controller
@SessionAttributes(value = {"newCustomer", "stateList", "phoneList"})
public class CreateCustomerController {

	@Autowired
	private CustomerService customerService;
	
	@Autowired
	Validator validator;
	
	public void setValidator(Validator validator) {
		this.validator = validator;
	}

	@SuppressWarnings("unchecked")
	@ModelAttribute
	public void referenceData(Map model) {
		model.put("phoneTypeList", PhoneType.values());
	}

	@RequestMapping("/createCustomer.html")
	public ModelAndView createCustomer() {
		
		Customer newCustomer = new Customer();
		ModelAndView mav = new ModelAndView("createCustomer");
		mav.addObject("newCustomer", newCustomer);
		List<State> stateList = customerService.getStateList();
		mav.addObject("stateList", stateList);
		return mav;
	}

	@RequestMapping("/createCustomerConfirm.html")
	public ModelAndView createCustomerConfirm(@RequestParam String submit,
			@ModelAttribute("newCustomer") Customer newCustomer,
			BindingResult result, HttpSession session) {

		Boolean available = customerService.usernameAvailable(newCustomer);
		if(available==false){
			return new ModelAndView("usernameUnavailable");
		}

		if ("Add Phone Number".equals(submit)) {
			PhoneNumber phoneNumber = new PhoneNumber();
			newCustomer.addPhoneNumber(phoneNumber);

			ModelAndView mav = new ModelAndView("createCustomer");
			mav.addObject("newCustomer", newCustomer);
			return mav;

		} else {
			
			validator.validate(newCustomer, result);

			if (result.hasErrors()) {
				return new ModelAndView("createCustomer");
			}
		}
		ModelAndView mav = new ModelAndView("createCustomerConfirm");
		mav.addObject("newCustomer", newCustomer);
		return mav;
	}

	@RequestMapping("/createCustomerSaved.html")
	public ModelAndView createCustomerSaved(
			@ModelAttribute("newCustomer") Customer newCustomer, BindingResult result) {
		


		customerService.save(newCustomer);

		ModelAndView mav = new ModelAndView("createCustomerSaved");
		mav.addObject("newCustomer", newCustomer);
		return mav;

	}
	


}
